package com.rederxu.browser;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.rederxu.farmer.BaseActivity;
import com.rederxu.farmer.R;
import com.rederxu.request.CookieStore;
import com.rederxu.tools.DisplayUtils;
import com.rederxu.tools.StringUtils;


/**
 * 若要自定义Title View.
 * <br/>文字标题必须为TextView，id通过title_text_id传入
 * <br/>返回按钮必须为ImageView，id通过title_back_id传入
 * */
@SuppressWarnings("deprecation")
public class BrowserActivity extends BaseActivity implements OnClickListener{

	private WebView webView = null;
	private ProgressBar loading = null;
	private EditText urlInput = null;
	private String url = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);    
		setContentView(R.layout.activity_browser);
		super.onCreate(savedInstanceState);
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void init() {
		url = getIntent().getStringExtra("url");
		if(url == null){
			showToast("没有网址找到网址");
			finish();
			return;
		}
		int titleCustomId = getIntent().getIntExtra("title_view_id", -1);
		if(titleCustomId != -1){
			View titleCustom = LayoutInflater.from(mContext).inflate(titleCustomId, null);
			if(titleCustom != null){
				findViewById(R.id.titleLayout).setVisibility(View.GONE);
				RelativeLayout titleCustomLayout = (RelativeLayout)findViewById(R.id.titleCustomLayout);
				titleCustomLayout.setVisibility(View.VISIBLE);
				titleCustomLayout.removeAllViews();
				titleCustomLayout.addView(titleCustom);
				int titleTextId = getIntent().getIntExtra("title_text_id", -1);
				if(titleTextId != -1){
					String titleStr = getIntent().getStringExtra("title");
					if(titleStr != null){
						TextView titleView = (TextView)titleCustom.findViewById(titleTextId);
						titleView.setText(titleStr);
					}
				}
				int backImgId = getIntent().getIntExtra("title_back_id", -1);
				if(backImgId != -1){
					ImageView back = (ImageView)titleCustom.findViewById(backImgId);
					back.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							finish();
						}
					});
				}
			}
		}
		webView = (WebView) findViewById(R.id.webView);
		loading = (ProgressBar) findViewById(R.id.loading);
		urlInput = (EditText) findViewById(R.id.urlInput);
		
		urlInput.setText(url);
		
		loading.setMax(100);
		webView.setWebViewClient(new WebViewClient(){
	           @Override
	        public boolean shouldOverrideUrlLoading(WebView view, String url) {
	            view.loadUrl(url);
	    		urlInput.setText(url);
	            return true;
	        }
	    });
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		webView.loadUrl(url);
		
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				// TODO Auto-generated method stub
				if (newProgress == 100) {
					loading.setVisibility(View.GONE);
					if(!urlInput.isFocused()){
						urlInput.setText(webView.getTitle());
					}
				} else {
					loading.setVisibility(View.VISIBLE);
					loading.setProgress(newProgress);
				}
			}
		});
		
		urlInput.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					String url = webView.getUrl();
					if(url != null){
						urlInput.setText(url);
					}else{
						urlInput.setText(BrowserActivity.this.url);
					}
				}else{
					String title = webView.getTitle();
					if(loading.getVisibility() == View.VISIBLE){
						urlInput.setText("加载中");
					}else{
						urlInput.setText(title);
					}
				}
			}
		});
		
		urlInput.setOnEditorActionListener(new OnEditorActionListener() {
			
			@SuppressLint("NewApi")
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId == EditorInfo.IME_ACTION_GO){
					String url = urlInput.getText().toString();
					if(!url.isEmpty()){
						webView.loadUrl(url);
					}
				}
				return false;
			}
		});
	}

	@Override
	public void initData() {
		syncCookies();
	}

	@Override
	public void onNetworkChanged(boolean isMobNetConnected,
			boolean isWifiConnected) {
		// TODO Auto-generated method stub

	}
	
	/** 
	 * 从HTTPRequest同步cookie 
	 */  
	@SuppressWarnings("deprecation")
	public void syncCookies() {  
		String url = CookieStore.getUrl(this);
		if(url == null){
			Log.i("syncCookies", "HTTPRequest 中没有cookie");
			return;
		}
		String cookies = CookieStore.getCookies(this);
		if(cookies == null || TextUtils.isEmpty(cookies)){
			Log.i("syncCookies", "HTTPRequest 中没有cookie");
			return;
		}
		Log.e("url/cookie", url + "\n" + cookies);
	    CookieSyncManager.createInstance(this);
	    CookieManager cookieManager = CookieManager.getInstance();  
	    cookieManager.setAcceptCookie(true);  
	    cookieManager.removeSessionCookie();
	    cookieManager.setCookie(url, cookies); 
	    CookieSyncManager.getInstance().sync();  
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onClick(View v) {
		//这里怎么swtich-case，报错：case expressions must be constant expressions，好诡异
		//故，改用if-else
		if(v.getId() == R.id.back){
			if (webView.canGoBack()) {
				webView.goBack();// 返回上一页面\
			} else {
				finish();
			}
		}else if(v.getId() == R.id.set){
			Log.e("showSetttingWindow", R.id.set + "");
			showSetttingWindow(v);
		}else if(v.getId() == R.id.layoutShare){
			Intent intent=new Intent(Intent.ACTION_SEND); 
			intent.setType("text/plain"); 
			intent.putExtra(Intent.EXTRA_SUBJECT, "分享"); 
			intent.putExtra(Intent.EXTRA_TEXT, webView.getTitle() + "。详情请点击：" + webView.getUrl() + "【" + getResources().getString(R.string.app_name) + "】");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			startActivity(Intent.createChooser(intent, getTitle())); 
		}else if(v.getId() == R.id.layoutClear){
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.removeAllCookie();
		    CookieSyncManager.getInstance().sync();  
		}else if(v.getId() == R.id.layoutJS){
			WebSettings settings = webView.getSettings();
			TextView tip = (TextView) v.findViewById(R.id.tipJS);
			boolean isJavaScriptEnabled = settings.getJavaScriptEnabled();
			if(isJavaScriptEnabled){
				settings.setJavaScriptEnabled(false);
				tip.setText("打开JS");
			}else{
				settings.setJavaScriptEnabled(true);
				tip.setText("关闭JS");
			}
			webView.reload();
		}else if(v.getId() == R.id.layoutImg){
			WebSettings settings = webView.getSettings();
			TextView tip = (TextView) v.findViewById(R.id.tipImg);
			boolean blockNetworkImage = settings.getBlockNetworkImage();
			if(!blockNetworkImage){
				settings.setBlockNetworkImage(true);
				tip.setText("打开图片");
			}else{
				settings.setBlockNetworkImage(false);
				tip.setText("关闭图片");
			}
			webView.reload();
		}else if(v.getId() == R.id.layoutBrowser){
			String url = webView.getUrl();
			if(StringUtils.isEmpty(url)){
				showToast("暂无地址");
				return;
			}
			Uri  uri = Uri.parse(url);
			Intent  intent = new  Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}else if(v.getId() == R.id.layoutRefresh){
			webView.reload();
		}
	} 
	
	public void showSetttingWindow(View v){
		 LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		 View view = layoutInflater.inflate(R.layout.view_set_browser_farmer, null);
		 WebSettings settings = webView.getSettings();
		 TextView tipJS = (TextView) view.findViewById(R.id.tipJS);
		 boolean isJavaScriptEnabled = settings.getJavaScriptEnabled();
		 if(isJavaScriptEnabled){
			 tipJS.setText("关闭JS");
		 }else{
			 tipJS.setText("打开JS");
		 }
		 TextView tipImg = (TextView) view.findViewById(R.id.tipImg);
		 boolean blockNetworkImage = settings.getBlockNetworkImage();
		 if(blockNetworkImage){
			 tipImg.setText("打开图片");
		 }else{
			 tipImg.setText("关闭图片");
		 }
		 int width = DisplayUtils.dipToPx(this, 152);
		 int height = ((LinearLayout)view).getChildCount() / 2;
		 height = DisplayUtils.dipToPx(this, 30) * (height + 1) + 1 * height;
		 PopupWindow popupWindow = new PopupWindow(view,width,height);
		 popupWindow.setBackgroundDrawable(new BitmapDrawable());
		 popupWindow.setFocusable(true);
	     popupWindow.setOutsideTouchable(true);
	     popupWindow.showAtLocation(v, Gravity.TOP,DisplayUtils.getScreenWidth(this) - width,DisplayUtils.dipToPx(this, 40) + DisplayUtils.getStatusHeight(this));
	}
}
